package com.jack.xiaoer.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.jack.xiaoer.entity.Category;
import com.jack.xiaoer.service.CategoryService;
import com.jack.xiaoer.util.AjaxResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/10.
 */
@RestController
@RequestMapping("/category")
public class CategoryController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(CategoryController.class);

    @Autowired
    private CategoryService categoryService;

    @PostMapping("/create")
    public AjaxResponse createCategory(@RequestBody @Validated Optional<Category> category, BindingResult bindingResult) {
        AjaxResponse validateResult = commonValidate(category, bindingResult);
        if (validateResult != null) {
            return validateResult;
        }

        Category cate = categoryService.createCategory(category);
        if (cate == null) {
            return AjaxResponse.fail("创建分类失败");
        }

        return AjaxResponse.success("创建分类成功", cate);
    }

    @GetMapping("/topCategory/{pageNum}/{size}")
    public AjaxResponse getTopCategory(@PathVariable("pageNum") Integer pageNum, @PathVariable("size") Integer pageSize) {
        Preconditions.checkArgument(pageNum > 0, "pageNum should be positive");
        Preconditions.checkArgument(pageSize > 0, "pageSize should be positive");

        IPage<Category> categoryPage = categoryService.listTopCategory(pageNum, pageSize);
        return AjaxResponse.success("获取首页分类成功", categoryPage);
    }


    @ExceptionHandler({IllegalArgumentException.class})
    public AjaxResponse handleIllegalParamters(IllegalArgumentException e) {
        return AjaxResponse.invalid(e.getMessage());
    }


}
